﻿using DevExpress.XtraEditors;
using MesProjectWinform.Equipment.Output;
using MesProjectWinform.Equipment.Select;
using MesProjectWinform.Public;
using MesProjectWinform.Public.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.Equipment.Form.ProjectFrom
{
    /// <summary>
    /// 添加项目表单窗体
    /// </summary>
    public partial class ProjectFromAddForm : DevExpress.XtraEditors.XtraForm
    {
        public ProjectFromAddForm()
        {
            InitializeComponent();
        }
        // 添加这个字段来存储选中的项目维护ID
        private List<long> selectedProjectMaintenanceIds = new List<long>();

        /// <summary>
        /// 关闭窗体按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ColseButton2_Click(object sender, EventArgs e)
        {
            //关闭窗体
            this.Close();
        }

        /// <summary>
        /// 加载下拉数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void ProjectFromAddForm_Load(object sender, EventArgs e)
        {
             LoadSelect();
        }
        /// <summary>
        /// 加载下拉数据
        /// </summary>
        public void LoadSelect()
        {
            #region  加载项目类型下拉框
                List<ProjectTypeOutput> projectTypeOutputs = new List<ProjectTypeOutput>()
                {
                    new ProjectTypeOutput()
                    {
                        Id = 1,
                        ProjectTypeName = "点检"
                    },
                    new ProjectTypeOutput()
                    {
                        Id = 2,
                        ProjectTypeName = "保养"
                    },
                };

            if (projectTypeOutputs != null)
            {
                //设备数据源
                ProjectType.Properties.DataSource = projectTypeOutputs;
                //设置显示的字段
                ProjectType.Properties.DisplayMember = "ProjectTypeName";

                //设置下拉列表的列
                ProjectType.Properties.Columns.Clear();
                ProjectType.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("ProjectTypeName", "类型名称"));

                ProjectType.Properties.NullText = "请选择项目表单类型";
            }
            #endregion

        }

        /// <summary>
        /// 保存点击按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void AddProjectFromButton1_Click(object sender, EventArgs e)
        {
            try
            {
                // 1. 数据验证
                // 名称非空验证
                if (string.IsNullOrWhiteSpace(ProjectName.Text))
                {
                    XtraMessageBox.Show("项目表单名称不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectName.Focus();
                    return;
                }

                // 名称长度验证
                if (ProjectName.Text.Length > 10)
                {
                    XtraMessageBox.Show("项目表单名称不能超过10个字符", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectName.Focus();
                    return;
                }

                // 项目类型非空验证
                if (ProjectType.EditValue == null)
                {
                    XtraMessageBox.Show("请选择项目表单类型", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectType.Focus();
                    return;
                }

                // 检验项目非空验证
                if (string.IsNullOrWhiteSpace(ProjectMaintenanceId.Text))
                {
                    XtraMessageBox.Show("请选择检验项目", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectMaintenanceId.Focus();
                    return;
                }

                // 描述长度验证
                if (ProjectDescription.Text.Length > 50)
                {
                    XtraMessageBox.Show("项目表单描述不能超过50个字符", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectDescription.Focus();
                    return;
                }

                // 添加调试输出，确认保存时ID列表是否正确
                Console.WriteLine($"保存时的项目维护ID列表: {string.Join(",", selectedProjectMaintenanceIds)}");

                ProjectFromOutput projectFromOutput = new ProjectFromOutput();

                projectFromOutput.ProjectName = ProjectName.Text.Trim();
                projectFromOutput.ProjectType = ProjectType.Text.Trim();
                // 修改：确保初始化ProjectMaintenanceIds列表
                projectFromOutput.ProjectMaintenanceIds = new List<long>();

                // 修改：将选中的项目维护ID添加到列表中
                if (selectedProjectMaintenanceIds != null && selectedProjectMaintenanceIds.Count > 0)
                {
                    projectFromOutput.ProjectMaintenanceIds = selectedProjectMaintenanceIds;
                }
                else
                {
                    // 如果没有选中项目，添加一个默认值或显示错误
                    XtraMessageBox.Show("请选择至少一个项目维护项", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                projectFromOutput.ProjectDescription = ProjectDescription.Text.Trim();
                projectFromOutput.CreatedBy = "admin";
                

               // 3. 调用API保存数据
               // 显示等待光标
               Cursor = Cursors.WaitCursor;

                // 调用API保存数据
                using (var client = new HttpClient())
                {
                    var json = JsonConvert.SerializeObject(projectFromOutput);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    // 异步调用API
                    var response = await client.PostAsync("http://localhost:5229/api/ProjectForm/AddProjectForm", content);

                    if (response.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show("添加成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        var errorContent = await response.Content.ReadAsStringAsync();
                        XtraMessageBox.Show($"添加失败: {errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"异常: {ex.Message}\n{ex.StackTrace}");
                XtraMessageBox.Show($"操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 点击选择按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectButton3_Click(object sender, EventArgs e)
        {
            // 创建项目维护选择窗体
            ProjectMaintenanceSelectForm projectMaintenanceSelectForm = new ProjectMaintenanceSelectForm();

            // 注册选择完成事件处理程序
            projectMaintenanceSelectForm.OnProjectMaintenanceSelected += ProjectMaintenanceSelectForm_OnProjectMaintenanceSelected;

            // 显示窗体
            projectMaintenanceSelectForm.ShowDialog();
        }

        /// <summary>
        /// 处理从ProjectMaintenanceSelectForm返回的选中数据
        /// </summary>
        /// <param name="selectedItems">选中的项目维护数据列表</param>
        private void ProjectMaintenanceSelectForm_OnProjectMaintenanceSelected(List<ProjectMaintenanceOutput> selectedItems)
        {
            if (selectedItems != null && selectedItems.Count > 0)
            {
                // 清空之前存储的ID列表
                selectedProjectMaintenanceIds.Clear();

                // 将选中项目的名称以逗号分隔拼接起来
                string selectedNames = string.Join(",", selectedItems.Select(item => item.ProjectMaintenanceName));

                // 收集所有选中项目的ID
                foreach (var item in selectedItems)
                {
                    selectedProjectMaintenanceIds.Add(item.Id);
                }

                // 设置到检验项目输入框中
                ProjectMaintenanceId.Text = selectedNames;
            }
        }

    }
}